package cn.market.service.product.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.market.bean.QueryResult;
import cn.market.bean.product.ProductType;
import cn.market.service.base.DaoSupport;
import cn.market.service.product.ProductTypeService;
import cn.market.utils.Log;


@Service
@Transactional
public class ProductTypeServiceBean extends DaoSupport<ProductType> implements ProductTypeService {
	private final String TAG = "ProductTypeServiceBean";
	@Override
	public void delete(Serializable ... entityids) {
		if(entityids!=null && entityids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0 ;i<entityids.length;i++){
				jpql.append("?").append(i+2).append(",");
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("update ProductType o set o.visible=?1 where o.typeid in("+ jpql.toString()+")")
			.setParameter(1, false);
			for(int i=0 ;i<entityids.length;i++){
				query.setParameter(i+2, entityids[i]);
			}
			query.executeUpdate();
		}
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<Integer> getSubTypeid(Integer[] parentids){
		if(parentids!=null && parentids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0; i<parentids.length; i++){
				jpql.append('?').append((i+1)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("select o.typeid from ProductType o where o.parent.typeid in("+ jpql.toString()+ ")");
			for(int i=0; i<parentids.length; i++){
				query.setParameter(i+1, parentids[i]);
			}
			return query.getResultList();
		}
		return null;
	}

	@Override
	public ProductType findProductTypeByNameAndMarketId(String name,
			Integer marketid) {
		String methodName = "findProductTypeByNameAndMarketId() -- the name is:"+name+"; the marketid is:"+marketid;
		Log.println(TAG, methodName);
		if(name == null || "".equals(name.trim()) || marketid==null)
			return null;
		String sql = "from ProductType o where o.name=?1 and o.belongToMarket.id=?2";
		Query query = em.createQuery(sql);
		query.setParameter(1, name);
		query.setParameter(2, marketid);
		ProductType type = (ProductType)query.getSingleResult();
		return type;
	}

	@Override
	public List<ProductType> getAllProductTypeByMarketId(Integer marketid) {
		String methodName = "getAllProductTypeByMarketId";
		Log.println(TAG, methodName+"-- marketid is :"+marketid);
		if(marketid == null)
			return null;
		List<ProductType> types = new ArrayList<ProductType>();
		String sql = "from ProductType o where o.belongToMarket.id=?1";
		Query query = em.createQuery(sql);
		query.setParameter(1, marketid);
		types = (List<ProductType>)query.getResultList();
		return types;
	}

	@Override
	public QueryResult<ProductType> producttypeSelectUI(String sql,
			String where, int first, int max, Object[] params,
			LinkedHashMap<String, String> orderby) {
		QueryResult<ProductType> qr = new QueryResult<ProductType>();
		String methodName = "producttypeSelectUI() ";
		List<ProductType> types = new ArrayList<ProductType>();
		List list = super.getScrollData(sql, where, first, max, params, orderby);
		if(list != null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Object [] obj=(Object [])list.get(i);
				ProductType type = new ProductType();
				type.setTypeid(new Integer(String.valueOf(obj[0])));
				type.setName(String.valueOf(obj[1]));
				types.add(type);
			}
			if(types.size()>0){
				StringBuffer sql2 = new StringBuffer("select t.typeid,t.parent.typeid from ProductType t where t.parent.typeid in (");
				Object [] parmas = new Object [types.size()];
				for(int i=0;i<types.size();i++){
					sql2.append("?").append(i+1).append(",");
					parmas[i]=types.get(i).getTypeid();
					//Log.println(TAG, methodName+" -- the params["+i+"] is:"+parmas[i]);
				}
				sql2.deleteCharAt(sql2.length()-1);
				sql2.append(") and t.visible=true");
				List child = super.getScrollData(sql2.toString(), null, -1, -1, parmas, null);
				//Log.println(TAG, methodName+" -- the child is:"+child);
				if(child!=null && child.size()>0){
					for(int i=0;i<types.size();i++){
						int parentid = types.get(i).getTypeid();
						Set<ProductType> childs = new HashSet<ProductType>();
						for(int j=0;j<child.size();j++){
							Object [] childobj=(Object [])child.get(j);
							ProductType childtype = new ProductType();
							int child_parentid = new Integer(String.valueOf(childobj[1]));
							int childid = new Integer(String.valueOf(childobj[0]));
							//Log.println(TAG, methodName+" -- the child_parentid is:"+child_parentid+"; the parentid is:"+parentid);
							if(child_parentid == parentid){
								childtype.setTypeid(childid);
								//childtype.setName(String.valueOf(childobj[1]));
								childs.add(childtype);
							}
							
						}
						if(childs.size()>0){
							types.get(i).setChildtypes(childs);
						}
						//Log.println(TAG, methodName+" -- the types.get(i).name is:"+types.get(i).getName()+" ; and the childs.size is:"+childs.size());
					}
				}
			}
			qr.setResultlist(types);
		}
		return qr;
	}
	
	
}
